/**
 * 测试工具和模拟数据
 */

import type {
  HistoryVersion,
  VersionEntries,
  FileEntry,
  FileHistoryRecord,
  FileStats,
  SearchResult,
  ContentSearchResult,
  ContentMatch
} from '../../types'

// 模拟历史版本数据
export const mockHistoryVersions: HistoryVersion[] = [
  {
    id: '-10363f99',
    timestamp: 1640995200000, // 2022-01-01 10:00:00
    fileCount: 3,
    hasEntriesFile: true
  },
  {
    id: '-139835d',
    timestamp: 1641081600000, // 2022-01-02 10:00:00
    fileCount: 2,
    hasEntriesFile: true
  },
  {
    id: '-14c7541d',
    timestamp: 1641168000000, // 2022-01-03 10:00:00
    fileCount: 1,
    hasEntriesFile: false
  }
]

// 模拟版本条目数据
export const mockVersionEntries: Record<string, VersionEntries> = {
  '-10363f99': {
    version: 1,
    resource: 'src/components/HelloWorld.vue',
    entries: [
      { id: 'hello.vue', timestamp: 1640995200000, source: 'editor' },
      { id: 'test.js', timestamp: 1640995200000 },
      { id: 'README.md', timestamp: 1640995200000, source: 'git' }
    ]
  },
  '-139835d': {
    version: 1,
    resource: 'src/utils/helper.ts',
    entries: [
      { id: 'helper.ts', timestamp: 1641081600000, source: 'editor' },
      { id: 'config.json', timestamp: 1641081600000 }
    ]
  }
}

// 模拟文件内容
export const mockFileContents: Record<string, string> = {
  '-10363f99:hello.vue': `<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <p>Welcome to Vue.js application</p>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  }
}
</script>

<style scoped>
.hello {
  color: #42b983;
}
</style>`,
  '-10363f99:test.js': `// Test file for unit testing
function testFunction() {
  console.log('Hello World')
  return true
}

function anotherFunction(param) {
  if (param) {
    return 'success'
  }
  return 'failure'
}

module.exports = { testFunction, anotherFunction }`,
  '-10363f99:README.md': `# Project Title

This is a sample project for testing search functionality.

## Features
- File search capability
- Content search with regex support
- Advanced search with multiple criteria
- History version management

## Installation
\`\`\`bash
npm install
npm start
\`\`\`

## Usage
Run the application and use the search interface.`,
  '-139835d:helper.ts': `export function formatDate(date: Date): string {
  return date.toISOString().split('T')[0]
}

export function validateEmail(email: string): boolean {
  const regex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/
  return regex.test(email)
}

export function debounce<T extends (...args: any[]) => any>(
  func: T,
  wait: number
): (...args: Parameters<T>) => void {
  let timeout: NodeJS.Timeout
  return (...args: Parameters<T>) => {
    clearTimeout(timeout)
    timeout = setTimeout(() => func.apply(this, args), wait)
  }
}`,
  '-139835d:config.json': `{
  "name": "test-project",
  "version": "1.0.0",
  "description": "A test project configuration",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "test": "jest"
  },
  "dependencies": {
    "vue": "^3.0.0",
    "typescript": "^4.0.0"
  }
}`
}

// 模拟文件统计信息
export const mockFileStats: Record<string, FileStats> = {
  '-10363f99:hello.vue': {
    size: mockFileContents['-10363f99:hello.vue'].length,
    modifiedTime: new Date(1640995200000),
    isDirectory: false
  },
  '-10363f99:test.js': {
    size: mockFileContents['-10363f99:test.js'].length,
    modifiedTime: new Date(1640995200000),
    isDirectory: false
  },
  '-10363f99:README.md': {
    size: mockFileContents['-10363f99:README.md'].length,
    modifiedTime: new Date(1640995200000),
    isDirectory: false
  },
  '-139835d:helper.ts': {
    size: mockFileContents['-139835d:helper.ts'].length,
    modifiedTime: new Date(1641081600000),
    isDirectory: false
  },
  '-139835d:config.json': {
    size: mockFileContents['-139835d:config.json'].length,
    modifiedTime: new Date(1641081600000),
    isDirectory: false
  }
}

// 模拟文件历史记录
export const mockFileHistory: FileHistoryRecord[] = [
  {
    versionId: '-10363f99',
    fileId: 'hello.vue',
    originalPath: 'src/components/HelloWorld.vue',
    timestamp: 1640995200000,
    source: 'editor',
    size: mockFileContents['-10363f99:hello.vue'].length,
    exists: true
  },
  {
    versionId: '-139835d',
    fileId: 'helper.ts',
    originalPath: 'src/utils/helper.ts',
    timestamp: 1641081600000,
    source: 'editor',
    size: mockFileContents['-139835d:helper.ts'].length,
    exists: true
  }
]

// 创建模拟搜索结果
export function createMockSearchResult(
  versionId: string,
  fileId: string,
  originalPath: string,
  matchScore: number = 0.8
): SearchResult {
  return {
    versionId,
    fileId,
    originalPath,
    fileName: fileId,
    timestamp: mockVersionEntries[versionId]?.entries.find(e => e.id === fileId)?.timestamp || Date.now(),
    matchScore
  }
}

// 创建模拟内容搜索结果
export function createMockContentSearchResult(
  versionId: string,
  fileId: string,
  originalPath: string,
  matches: ContentMatch[],
  matchScore: number = 0.8
): ContentSearchResult {
  return {
    ...createMockSearchResult(versionId, fileId, originalPath, matchScore),
    matches
  }
}

// 创建模拟内容匹配
export function createMockContentMatch(
  lineNumber: number,
  lineContent: string,
  matchStart: number,
  matchEnd: number,
  context: string[] = []
): ContentMatch {
  return {
    lineNumber,
    lineContent,
    matchStart,
    matchEnd,
    context
  }
}

// 测试工具函数
export class TestUtils {
  /**
   * 等待指定时间
   */
  static async delay(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms))
  }

  /**
   * 创建临时文件路径
   */
  static createTempPath(filename: string): string {
    return `/tmp/test-${Date.now()}-${filename}`
  }

  /**
   * 验证搜索结果排序
   */
  static validateSearchResultOrder(results: SearchResult[]): boolean {
    for (let i = 1; i < results.length; i++) {
      if (results[i - 1].matchScore < results[i].matchScore) {
        return false
      }
    }
    return true
  }

  /**
   * 生成随机字符串
   */
  static randomString(length: number = 10): string {
    const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    let result = ''
    for (let i = 0; i < length; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length))
    }
    return result
  }

  /**
   * 创建大量测试数据
   */
  static createLargeDataset(count: number): HistoryVersion[] {
    const versions: HistoryVersion[] = []
    const baseTime = Date.now()
    
    for (let i = 0; i < count; i++) {
      versions.push({
        id: `-test${i.toString(16)}`,
        timestamp: baseTime - (i * 60000), // 每个版本间隔1分钟
        fileCount: Math.floor(Math.random() * 10) + 1,
        hasEntriesFile: Math.random() > 0.2 // 80%的版本有entries文件
      })
    }
    
    return versions
  }

  /**
   * 验证错误对象结构
   */
  static validateErrorStructure(error: any): boolean {
    return (
      error &&
      typeof error.type === 'string' &&
      typeof error.message === 'string' &&
      error.timestamp instanceof Date &&
      typeof error.recoverable === 'boolean'
    )
  }

  /**
   * 创建性能测试包装器
   */
  static async measurePerformance<T>(
    operation: () => Promise<T>,
    name: string = 'operation'
  ): Promise<{ result: T; duration: number }> {
    const startTime = performance.now()
    const result = await operation()
    const duration = performance.now() - startTime
    
    console.log(`${name} took ${duration.toFixed(2)}ms`)
    
    return { result, duration }
  }

  /**
   * 创建内存使用监控器
   */
  static createMemoryMonitor(): {
    start: () => void
    stop: () => { initial: number; final: number; delta: number }
  } {
    let initialMemory = 0
    
    return {
      start: () => {
        if (typeof process !== 'undefined' && process.memoryUsage) {
          initialMemory = process.memoryUsage().heapUsed
        }
      },
      stop: () => {
        if (typeof process !== 'undefined' && process.memoryUsage) {
          const finalMemory = process.memoryUsage().heapUsed
          return {
            initial: initialMemory,
            final: finalMemory,
            delta: finalMemory - initialMemory
          }
        }
        return { initial: 0, final: 0, delta: 0 }
      }
    }
  }
}

// 模拟数据生成器
export class MockDataGenerator {
  /**
   * 生成模拟的Vue组件内容
   */
  static generateVueComponent(componentName: string): string {
    return `<template>
  <div class="${componentName.toLowerCase()}">
    <h1>{{ title }}</h1>
    <p>{{ description }}</p>
  </div>
</template>

<script>
export default {
  name: '${componentName}',
  data() {
    return {
      title: '${componentName} Component',
      description: 'This is a generated component for testing'
    }
  }
}
</script>

<style scoped>
.${componentName.toLowerCase()} {
  padding: 20px;
  border: 1px solid #ccc;
}
</style>`
  }

  /**
   * 生成模拟的TypeScript文件内容
   */
  static generateTypeScriptFile(fileName: string): string {
    return `/**
 * ${fileName} - Generated for testing
 */

export interface ${fileName}Interface {
  id: string
  name: string
  timestamp: number
}

export class ${fileName}Class implements ${fileName}Interface {
  constructor(
    public id: string,
    public name: string,
    public timestamp: number = Date.now()
  ) {}

  public toString(): string {
    return \`\${this.name} (\${this.id})\`
  }

  public isValid(): boolean {
    return this.id.length > 0 && this.name.length > 0
  }
}

export function create${fileName}(id: string, name: string): ${fileName}Class {
  return new ${fileName}Class(id, name)
}

export default ${fileName}Class`
  }

  /**
   * 生成模拟的JSON配置文件
   */
  static generateJsonConfig(projectName: string): string {
    return JSON.stringify({
      name: projectName,
      version: '1.0.0',
      description: `Configuration for ${projectName}`,
      main: 'index.js',
      scripts: {
        start: 'node index.js',
        build: 'webpack --mode=production',
        test: 'jest',
        dev: 'webpack-dev-server'
      },
      dependencies: {
        vue: '^3.0.0',
        typescript: '^4.0.0',
        webpack: '^5.0.0'
      },
      devDependencies: {
        jest: '^27.0.0',
        '@types/node': '^16.0.0'
      }
    }, null, 2)
  }
}